import OSS from 'ali-oss'

type Callback = (data: any) => void

export class UploadFile {
  static instance: UploadFile | null = null
  private oss_client: OSS | null = null
  private is_client = false

  static getInstance() {
    return this.instance ?? (this.instance = new UploadFile())
  }

  constructor() {
    this.client()
  }

  async client() {
    this.is_client = true
    try {
      // const res = await getOssStsToken()
      const res = await fetch('https://api.guoruiyu.cn/index.php/system/v1/getOssStsToken')
      const json = await res.json()
      if (json.code == 200) {
        const config = json.data
        this.oss_client = new OSS({
          endpoint: config.domain,
          region: config.region,
          accessKeyId: config.AccessKeyId,
          accessKeySecret: config.AccessKeySecret,
          bucket: config.bucket,
          stsToken: config.SecurityToken,
          cname: true
        })
      }
    } catch (e) {
      console.log(e)
    }
    this.is_client = false
  }

  async uploadFile(file: File, progress: Callback) {
    if (!this.oss_client && !this.is_client) await this.client()
    try {
      const result: any = await this.oss_client?.multipartUpload(file.name, file, {
        progress: (p) => {
          progress(p)
        }
      })
      console.log('result', result)
      return result.res.requestUrls[0]?.split('?')[0]
    } catch (error) {
      this.oss_client = null
      await this.uploadFile(file, progress)
    }
  }
}

const uploadFile = UploadFile.getInstance()

export default uploadFile
